package com.seisys.controller.system.menu;


import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seisys.controller.base.BaseController;
import com.seisys.entity.system.Menu;
import com.seisys.entity.system.Role;
import com.seisys.entity.system.User;
import com.seisys.service.system.LogService;
import com.seisys.service.system.menu.MenuService;
import com.seisys.service.system.role.RoleService;
import com.seisys.util.LogUtil;
import com.seisys.util.PageData;
import com.seisys.util.RightsHelper;
import com.seisys.util.Tools;

import net.sf.json.JSONArray;


/**
 * 类名称：MenuController 创建人：FH 创建时间：2014年7月1日
 * 
 * @version
 */
@Controller
@RequestMapping(value = "/menu")
public class MenuController extends BaseController
{
    private static final String MODULENAME = "菜单管理";

    @Resource(name = "menuService")
    private MenuService menuService;

    @Resource(name = "logService")
    private LogService logService;

    @Resource(name = "roleService")
    private RoleService roleService;

    /**
     * 显示菜单列表
     * 
     * @param model
     * @return
     */
    @RequestMapping
    public ModelAndView list()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        try
        {
            List<Menu> menuList = menuService.listAllParentMenu();
            mv.addObject("menuList", menuList);
            mv.setViewName("system/menu/menu_list");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }

        return mv;
    }

    /**
     * 请求新增菜单页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/toAdd")
    public ModelAndView toAdd()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        try
        {
            List<Menu> menuList = menuService.listAllMenuForSelect();
            mv.addObject("menuList", menuList);
            mv.setViewName("system/menu/menu_add");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 保存菜单信息
     * 
     * @param menu
     * @param model
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView add(Menu menu)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try
        {
            menu.setMENU_ID(String.valueOf(
                Integer.parseInt(menuService.findMaxId(pd).get("MID").toString()) + 1));

            String[] PARENT_INFO = menu.getPARENT_ID().split(",");
            String PARENT_ID = PARENT_INFO[0];
            String PARENT_TYPE = "";
            if (!"0".equals(PARENT_ID))
            {
                // 处理菜单类型====
            	PARENT_TYPE = PARENT_INFO[1];
                pd.put("MENU_ID", PARENT_ID);
                pd = menuService.getMenuById(pd);
            }
            menu.setMENU_TYPE(PARENT_TYPE.equals("X") ? "Y" : "Z");
            menu.setPARENT_ID(PARENT_ID);
            menuService.saveMenu(menu);
            // 将此次操作记录到数据库中
            updateRoleRights(request);// 更新系统管理员权限
            LogUtil.getInstance().operationLogger(LogUtil.ADD, MODULENAME, menu.getMENU_ID(),
                logService, request);
            mv.addObject("msg", "success");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }

        mv.setViewName("save_result");
        return mv;

    }

    /**
     * 请求编辑菜单页面
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(String MENU_ID)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            pd.put("MENU_ID", MENU_ID);
            pd = menuService.getMenuById(pd);
            List<Menu> menuList = menuService.listAllParentMenu();
            mv.addObject("menuList", menuList);
            mv.addObject("pd", pd);
            mv.setViewName("system/menu/menu_edit");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 请求编辑菜单图标页面
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/toEditicon")
    public ModelAndView toEditicon(String MENU_ID)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            pd.put("MENU_ID", MENU_ID);
            mv.addObject("pd", pd);
            mv.setViewName("system/menu/menu_icon");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 保存菜单图标 (顶部菜单)
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/editicon")
    public ModelAndView editicon()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            pd = menuService.editicon(pd);
            mv.addObject("msg", "success");
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 保存编辑
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            String PARENT_ID = pd.getString("PARENT_ID");
            if (null == PARENT_ID || "".equals(PARENT_ID))
            {
                PARENT_ID = "0";
                pd.put("PARENT_ID", PARENT_ID);
            }
            String menuId = pd.getString("MENU_ID");
            pd = menuService.edit(pd);

            updateRoleRights(request);// 更新系统管理员权限
            LogUtil.getInstance().operationLogger(LogUtil.UPDATE, MODULENAME, menuId, logService,
                request);
            mv.addObject("msg", "success");

        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 获取当前菜单的所有子菜单
     * 
     * @param menuId
     * @param response
     */
    @RequestMapping(value = "/sub")
    public void getSub(@RequestParam String MENU_ID, HttpServletResponse response)
        throws Exception
    {
        try
        {
            List<Menu> subMenu = menuService.listSubMenuByParentId(MENU_ID);
            JSONArray arr = JSONArray.fromObject(subMenu);
            PrintWriter out;

            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            String json = arr.toString();
            out.write(json);
            out.flush();
            out.close();
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 删除菜单
     * 
     * @param menuId
     * @param out
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public String delete(@RequestParam String MENU_ID, PrintWriter out)
        throws Exception
    {

        try
        {
            menuService.deleteMenuById(MENU_ID);
            LogUtil.getInstance().operationLogger(LogUtil.DELETE, MODULENAME, MENU_ID, logService,
                request);
           return "success";
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            return "error";
        }

    }

    // 更新权限
    public void updateRoleRights(HttpServletRequest request)
    {
        try
        {
            User user = (User)request.getSession().getAttribute("sessionUser");
            String roleId = user.getROLE_ID();
            if ("1".equals(roleId))
            {
                List<String> menuIds = menuService.getAllMenuId();
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < menuIds.size(); i++ )
                {
                    if (i < menuIds.size() - 1)
                    {
                        sb.append(menuIds.get(i)).append(",");
                    }
                    else
                    {
                        sb.append(menuIds.get(i));
                    }
                }
                String menuIdss = sb.toString();
                BigInteger rights = RightsHelper.sumRights(Tools.str2StrArray(menuIdss));
                Role role = roleService.getRoleById(roleId);
                role.setRIGHTS(rights.toString());
                roleService.updateRoleRights(role);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    // public static void main(String[] args) {
    // String str =
    // "1,24";
    // BigInteger rights = RightsHelper.sumRights(Tools.str2StrArray(str));
    // System.out.println(rights);
    // }
}
